<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Validation Class - Fuel Documentation</title>
	<link href="../assets/css/main.css" media="screen" rel="stylesheet" />
	<script type="text/javascript" src="../assets/js/jquery-1.4.4.min.js"></script>
	<script type="text/javascript" src="../assets/js/nav.js"></script>
	<script type="text/javascript" src="../assets/js/highlight.pack.js"></script>
	<script type="text/javascript">
		$(function() {
			show_nav('classes', '../');
		});
		hljs.tabReplace = '    ';
		hljs.initHighlightingOnLoad();
	</script>
</head>
<body>

	<header>
		<h1>Fuel Documentation</h1>
	</header>

	<div id="main-nav"></div>

	<section id="content">
		<h2>Validation Class</h2>

		<p>The Validation class helps you validate user input, if you want to create a form &amp; its validation at
			the same time use the <a href="fieldset.html">Fieldset</a> class instead.</p>

		<ul>
			<li><a href="#usage">Usage</a></li>
			<li><a href="#rules">Validation rules</a></li>
			<li><a href="#errors">Error messages</a></li>
			<li><a href="#methods">All methods</a></li>
		</ul>

		<article>
			<h3><a name="usage">Usage</a></h3>

			<p>To start validation you need to create an object, this can be the default object named "default" or
			you can name it if you need multiple validation objects.</p>

			<pre class="php"><code>// Use default
$val = Validation::factory();

// ... or name it
$val = Validation::factory('my_validation');</code></pre>

			<p>After having it instantiated you can start adding fields to it. This works exactly like the when using
			the Fieldset class, however here we'll only document the preferred usage.</p>

			<pre class="php"><code>$val = Validation::factory('my_validation');

// Add a field for username, give it the label "Your username" and make it required
$val->add('username', 'Your username')->add_rule('required');

// Now add another field for password, and require it to contain at least 3 and at most 10 characters
$val->add('password', 'Your password')->add_rule('required')
    ->add_rule('min_length', 3)
    ->add_rule('max_length', 10);</code></pre>

			<p>The first parameter of the add_rule() method can contain PHP native function names, any valid PHP
			callback and Closures in addition to the provided validation methods. The method will get the value to
			be validated as its first argument and any further arguments can be given to the add_rule() method.</p>

			<p>We also provide a shorter syntax which is very limited in comparison. It will not accept array-callbacks,
			closures or parameters other then strings.</p>

			<pre class="php"><code>// The same fields as the example above
$val = Validation::factory('my_validation');
$val->add_field('username', 'Your username', 'required');
$val->add_field('password', 'Your password', 'required|min_length[3]|max_length[10]');</code></pre>

			<p>Once all the fields have been added you can run your validation. This will default to $_POST input, but
			can be extended and overwritten when given an input array.</p>

			<pre class="php"><code>// run validation on just post
if ($val->run())
{
	// process your stuff when validation succeeds
}
else
{
	// validation failed
}

// alternative to above, overwriting the username in post, password will still be sought in post
if ($val->run(array('username' => 'something')))</code></pre>

			<p>When validation is ran there are three methods available for information about the input:</p>

			<pre class="php"><code>// get an array of successfully validated fields => value pairs
$vars = $val->validated();
// get an array of validation errors as field => error pairs
$errors = $val->errors();
// get an array of the input that was validated, this merged the post & input given to run()
$input = $val->input();

// all these methods can also get just the value for a single field
$var = $val->validated('username');</code></pre>

			<p>Validation can also run partially, in that case even required fields are ignored when they're not in
			POST or the input given to run(). One does this by setting the 2nd parameter of run to true.</p>

			<pre class="php"><code>// this will only validate the password when username isn't present in post
$val->run(array('password' => 'whatever'), true);</code></pre>
		</article>

		<article>
			<h3><a name="rules">Validation rules</a></h3>

			<p>Note that all methods (even min_length) will also return true on empty input. To also require the field
			you must add the rule "required" as well.</p>

			<p>All these rules can be used like below:</p>
			<pre class="php"><code>// example normal usage with rule without and one with params
$val->add('email', 'Email address')->add_rule('match_value', 'me@mydomain.com', true)->add_rule('valid_email');
$val->add_field('email', 'Email address', 'match_value[me@mydomain.com,1]|valid_email');</code></pre>

			<h4>Rules table</h4>
			<table class="config">
				<tbody>
					<tr class="header">
						<th>Rule</th>
						<th>Additional parameters</th>
						<th>Description</th>
					</tr>
					<tr>
						<th>required</th>
						<td>(none)</td>
						<td>
							The field must be set and have been given something other than <kbd>null</kbd>,
							<kbd>false</kbd> or empty string.
						</td>
					</tr>
					<tr>
						<th>match_value</th>
						<td><kbd>$compare</kbd>, <kbd>$strickt</kbd> = false</td>
						<td>
							The field input must match <kbd>$compare</kbd>, will be done using == unless 2nd parameter
							is also given as true (then === is used).
						</td>
					</tr>
					<tr>
						<th>match_pattern</th>
						<td><kbd>$pattern</kbd></td>
						<td>
							Will try to match the value against the given $pattern which must be a full PREG regex.
						</td>
					</tr>
					<tr>
						<th>match_field</th>
						<td><kbd>$field</kbd></td>
						<td>
							Will try to match the field to the field with the given fieldname, the matching is done
							using ===.<br />
							<strong>Important:</strong> you can only match against a field that was added before the
							field this rule is added to.
						</td>
					</tr>
					<tr>
						<th>min_length</th>
						<td><kbd>$length</kbd></td>
						<td>
							Tests whether the string contains at least <kbd>$length</kbd>'s number of character.
						</td>
					</tr>
					<tr>
						<th>max_length</th>
						<td><kbd>$length</kbd></td>
						<td>
							Tests whether the string contains no more than <kbd>$length</kbd>'s number of character.
						</td>
					</tr>
					<tr>
						<th>exact_length</th>
						<td><kbd>$length</kbd></td>
						<td>
							Tests whether the string has precisely <kbd>$length</kbd>'s number of character.
						</td>
					</tr>
					<tr>
						<th>valid_email</th>
						<td>(none)</td>
						<td>
							Validates if the given input is a valid email address.
						</td>
					</tr>
					<tr>
						<th>valid_emails</th>
						<td>(none)</td>
						<td>
							Validates multiple email addresses separated by commas.
						</td>
					</tr>
					<tr>
						<th>valid_url</th>
						<td>(none)</td>
						<td>
							Validates if the given input is a valid URL.
						</td>
					</tr>
					<tr>
						<th>valid_ip</th>
						<td>(none)</td>
						<td>
							Validates if the given input is a valid IP.
						</td>
					</tr>
					<tr>
						<th>numeric_min</th>
						<td><kbd>$min_val</kbd></td>
						<td>
							Tests whether the given input is a number that is greater than <kbd>$min_val</kbd>.
						</td>
					</tr>
					<tr>
						<th>numeric_max</th>
						<td><kbd>$max_val</kbd></td>
						<td>
							Tests whether the given input is a number that is smaller than <kbd>$max_val</kbd>.
						</td>
					</tr>
					<tr>
						<th>valid_string</th>
						<td><kbd>$flags</kbd> = array('alpha', 'utf8')</td>
						<td>
							See below.
						</td>
					</tr>
				</tbody>
			</table>

			<h4>Valid string rule</h4>
			<p>Validates whether a string adheres to the conditions set by the $flags parameter. The accepted flags
			are:</p>
			<table class="config">
				<tbody>
					<tr class="header">
						<th>Flag</th>
						<th>Description</th>
					</tr>
					<tr>
						<th>alpha</th>
						<td>Allow alphabetical characters.</td>
					</tr>
					<tr>
						<th>uppercase</th>
						<td>Used in combination with alpha to only allow uppercase characters.</td>
					</tr>
					<tr>
						<th>lowercase</th>
						<td>Used in combination with alpha to only allow lowercase characters.</td>
					</tr>
					<tr>
						<th>numeric</th>
						<td>Allow numeric characters.</td>
					</tr>
					<tr>
						<th>spaces</th>
						<td>Allow normal spaces.</td>
					</tr>
					<tr>
						<th>newlines</th>
						<td>Allow newline character.</td>
					</tr>
					<tr>
						<th>tabs</th>
						<td>Allow tabs.</td>
					</tr>
					<tr>
						<th>dots</th>
						<td>Allow dots.</td>
					</tr>
					<tr>
						<th>punctuation</th>
						<td>Allow dots, commas, exclamation marks, question marks, colons and semi-colons.</td>
					</tr>
					<tr>
						<th>dashes</th>
						<td>Allow dashes and underscores.</td>
					</tr>
					<tr>
						<th>utf8</th>
						<td>Adds UTF8 modifier to regex.</td>
					</tr>
				</tbody>
			</table>
		</article>

		<article>
			<h3><a name="errors">Error messages</a></h3>

			<p>Error messages are set using a language file "validation.php" which is loaded automatically.</p>

			<p>There are 2 ways of manipulating the error messages during validation.</p>

			<pre class="php"><code>// change a rule per validation object
$val->set_message('required', 'The field :label is required.');

// or per error
echo $val->errors('username')->get_message('The field :label must be filled out before auth is attempted.');
// Outputs "The field Your username must be filled out before auth is attempted." when validation for username
// failed, or nothing when not yet validated or validation succeeded.</code></pre>

			<p>As you may have noticed the error messages accept a couple of variables that are replaced by the
			field's properties. Below is a list of the available variables:</p>

			<table class="config">
				<tbody>
					<tr class="header">
						<th>Variable</th>
						<th>Description</th>
					</tr>
					<tr>
						<th>:field</th>
						<td>Will be substituted by the field's name.</td>
					</tr>
					<tr>
						<th>:label</th>
						<td>Will be substituted by the field's label.</td>
					</tr>
					<tr>
						<th>:value</th>
						<td>Will be substituted by the field's value which could not be validated.</td>
					</tr>
					<tr>
						<th>:rule</th>
						<td>Will be substituted by the rule that failed. The included rules will be just their name,
						others will be the string callback or classname:method (which will also be the key for which
						you must add a validation rule if you want to).</td>
					</tr>
					<tr>
						<th>:param:1</th>
						<td>Will be replaced by the first additional parameter's value, :param:2 will be the second,
						etc.</td>
					</tr>
				</tbody>
			</table>
		</article>

		<article>
            <h3><a name="methods">Extending Validation class</a></h3>

            <p>There are few approaches to extend the validation class:</p>

            <p>1. To extend the core class like described in the <a href="../general/extending_core.html">Extending Core Classes</a></p>

            <p>2. To create a class in <b>app/classes/myvalidation.php</b> (for example)</p>
            <pre class="php"><code>// app/classes/myvalidation.php
class Myvalidation {

    public function _validation_unique($val, $options)
    {
        list($table, $field) = explode('.', $options);

        $result = DB::select("LOWER (\"$field\")")
            ->where("$field", '=', MBSTRING ? mb_strtolower($val) : strtolower($val))
            ->from($table)->execute();

        if($result->count() > 0)
            return false;
        else
            return true;
    }

}

// and call it like:
$val = Validation::factory();
$val->add_callable('myvalidation'); // here we add the class to load rules from

$val->add_field('username', 'Your username', 'trim|strip_tags|required|unique[users.username]');</code></pre>

        <p>3. Calling callbacks from a model. It works like a method described above, but we only need to call it in other way:</p>
<pre class="php"><code>$val = Validation::factory();
$val->add_model('Model_User');</code></pre>

        <p class="note">
        <strong>Note: </strong>
        You need the '_validation_' prefix for a method to be used in validation.
        </p>
        </article>

        <article>
			<h3><a name="methods">All methods</a></h3>

			<p>To be written.</p>
		</article>

	</section>

	<section id="footer">
		<p>
			<a href="http://fuelphp.com">Fuel</a> is released under the MIT license.<br />
			&copy; 2010 - 2011 Fuel Development Team
		</p>
	</section>

</body>
</html>
